#!/usr/bin/env python

"""
Subversion post-commit hook for Longhouse.

Notifies Longhouse that it should perform a 'svn up'
action and load changes from XML. 

Copy this script to the /hooks directory in your repository.
Be sure to chmod it to be executable.

See the Subversion book for more information about installing hooks:
http://svnbook.red-bean.com/en/1.4/svn.reposadmin.create.html#svn.reposadmin.create.hooks
"""

import urllib, sys, os


def main():

    project_urls = [] # you can add your projects here
    errors = []

    # walk the current directory
    for (root, dirs, files) in os.walk(os.path.dirname(__file__)):
        
        # remove any hidden directories
        for dir in dirs:
            if dir.startswith('.'):
                dirs.remove(dir)
                
        # read the first line of each file ending in .longhouse   
        for file in files:
            if file.endswith('longhouse'):
                
                f = open( os.path.join( root, file ) )
                
                new_url = f.readline().strip()
                
                # make sure the url ends in a forward slash '/'
                if not new_url.endswith('/'):
                    new_url += '/'
                
                project_urls.append(new_url)
    
    
    # send a GET to each url + /svnup
    for project_url in project_urls:
        
        try:
            page = urllib.urlopen(project_url + 'svnup').read()
            
            # Anything other than 'Done.' is considered an error
            if not page == 'Done.':
                errors.append(project_url)
        
        except:
            errors.append(project_url)

    # if there were any errors, write error info to stderr
    if len(errors) > 0:        
        err_msg  = \
'Problems were encountered updating the following Longhouse projects:\n'

        for error in errors:
            err_msg += '\t' + error + '\n'
            
        sys.stderr.write(err_msg)
        sys.exit(1)
        
    
if __name__ == '__main__':
    main()
